<template>
    <div>
        <div class="">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="选择周次">
                    <el-date-picker v-model="searchForm.week" type="week" format="YYYY年 第ww周" value-format="YYYY-ww"
                        placeholder="选择周次" @change="getActivityUserWeeklySummary" />
                </el-form-item>
                <el-form-item label="选择成员">
                    <el-select v-model="searchForm.userIds" multiple collapse-tags collapse-tags-tooltip filterable
                        clearable placeholder="选择成员" @change="getActivityUserWeeklySummary">
                        <el-option v-for="user in teamusers" :key="user.ID"
                            :label="user.user?.xingming ? `${user.user.xingming} (${user.user?.name})` : user.user?.name"
                            :value="user.userid" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="start">搜索</el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- <AIWarningTips :show="true" /> -->
        <el-table :data="userWeeklySummaries" height="67vh" style="width: 100%" border v-loading="loading">
            <template v-slot:empty>
                <el-empty image="https://cdn-hterobot.oss-cn-qingdao.aliyuncs.com/image/ojSass-empty.png" />
            </template>
            <el-table-column prop="username" label="成员" width="" fixed />
            <el-table-column prop="year" label="年份" width=""></el-table-column>
            <el-table-column prop="week" label="周次" width="">
                <template #default="{ row }">
                    第{{ row.week }}周 ({{ getWeekDateRange(row.year, row.week) }})
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="">
                <template #default="{ row }">
                    {{ formatDate(row.createdAt) }}
                </template>
            </el-table-column>
            <el-table-column prop="updatedAt" label="更新时间" width="">
                <template #default="{ row }">
                    {{ formatDate(row.updatedAt) }}
                </template>
            </el-table-column>
            <el-table-column prop="content" label="操作" width="100">
                <template #default="{ row }">
                    <el-button type="primary" size="default" @click="showDetail(row)">查看</el-button>
                    <!-- <div class="markdown-content markdown-body" v-html="renderMarkdown(row.content)" /> -->
                </template>
            </el-table-column>
        </el-table>
        <el-pagination class="pager" size="default" :page-size="limit" :page-sizes="pageSizes" :total="totalCount"
            layout="total, sizes, prev, pager, next" @current-change="changePage" @size-change="handleSizeChange"
            :current-page="Math.floor(offset / limit) + 1">
        </el-pagination>
        <!-- 详情弹窗 -->
        <el-dialog v-model="detailVisible" :title="detailTitle" width="70%" :key="currentDetail?.id">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    {{ detailTitle }}
                </span>
            </template>
            <!-- <div class="markdown-container markdown-body" v-html="renderMarkdown(currentDetail.content)"></div> -->
            <UserWeeklySummary :content="content"></UserWeeklySummary>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs';
import isoWeek from 'dayjs/plugin/isoWeek';
import weekOfYear from 'dayjs/plugin/weekOfYear';
import { ElMessage } from "element-plus";
import "github-markdown-css/github-markdown-light.css";
import MarkdownIt from 'markdown-it';
import mermaid from 'mermaid';
import { nextTick, onMounted, ref } from 'vue';
import { useStore } from 'vuex';
import { asyncGetActivityUserWeeklySummary, asyncselectteamuser } from '../../../api';
import UserWeeklySummary from '../../../components/AI/userWeeklySummary.vue';
import { Storekey } from '../../../interface';
import Studycodemodel from '../../../mysql_interface/studycodemodel';

dayjs.extend(isoWeek);
dayjs.extend(weekOfYear);
// 设置周一为一周的第一天（1-6表示周一到周六，0是周日）
dayjs.locale('zh-cn', { weekStart: 1 })

const p = defineProps<{ ID: number, team: Studycodemodel.Iteam, group: Studycodemodel.Iteamusergroup[] }>()

const store = useStore(Storekey);

const loading = ref(false);
const limit = ref(20)
const offset = ref(0)
const pageSizes: number[] = [limit.value, 50, 100, 200, 400, 500, 1000, 2000]
const totalCount = ref(0);

const teamusers = ref<Studycodemodel.Iteamuser[]>([]);
const userWeeklySummaries = ref<any[]>([]);
const searchForm = ref({
    week: '',
    userIds: [] as number[]
});
onMounted(() => { start(); });
async function start() {
    await getusers();
    getActivityUserWeeklySummary();
}
async function getusers() {
    try {
        const data = await asyncselectteamuser({ teamid: p.ID });
        teamusers.value = data.rows;
    } catch (error) {
        console.error(error);
        ElMessage.error('获取团队成员失败');
    }
}
async function getActivityUserWeeklySummary() {
    loading.value = true;
    try {
        const [year, week] = searchForm.value.week ? searchForm.value.week.split('-').map(Number) : [undefined, undefined];
        const params = {
            userid: searchForm.value.userIds.length ? searchForm.value.userIds : teamusers.value.map((u) => u.userid),
            year,
            week,
        };
        const { count, rows } = await asyncGetActivityUserWeeklySummary(params);
        userWeeklySummaries.value = rows;
        totalCount.value = count;
    } catch (error) {
        // ElMessage.error('获取周总结数据失败');
        console.error(error);
    } finally {
        loading.value = false;
    }
}

function formatDate(dateString: string) {
    return new Date(dateString).toLocaleString();
}
function changePage(val: number) {
    offset.value = limit.value * (val - 1);
    start()
}
const handleSizeChange = (val: number) => {
    limit.value = val
    start()
}

// 计算指定年份和周数的日期范围
function getWeekDateRange(year: number, week: number) {
    const startDate = dayjs().year(year).isoWeek(week).startOf('week').add(1, 'day') // 周一
    // 获取该年的第一天
    const firstDay = dayjs(`${year}-01-01`);
    // 找到该年第 `week` 周的开始日期（周一）
    const startOfWeek = firstDay.isoWeek(week).startOf('isoWeek').format('YYYY-MM-DD');
    // 找到该年第 `week` 周的结束日期（周日）
    const endOfWeek = firstDay.isoWeek(week).endOf('isoWeek').format('YYYY-MM-DD');

    return `${startOfWeek}~${endOfWeek}`;
}

// 新增弹窗相关状态
const detailVisible = ref(false)
const detailTitle = ref('')
const content = ref('')
const currentDetail = ref<any>(null)

// 显示详情弹窗
function showDetail(row: any) {
    currentDetail.value = row
    detailTitle.value = `${row.username} - ${row.year}年第${row.week}周总结`
    content.value = row.content
    detailVisible.value = true
}

// Markdown 解析器
const md = new MarkdownIt({
    breaks: true,
    html: true,
    linkify: true
});

function renderMarkdown(content: string) {
    if (!content) return "";
    let html = md.render(content);

    // 替换 Mermaid 代码块
    html = html.replace(
        /<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,
        (_, code) => `<div class="mermaid">${code}</div>`
    );

    // 等待 DOM 更新后渲染 Mermaid
    nextTick(() => {
        mermaid.init(undefined, document.querySelectorAll(".mermaid"));
    });

    return html;
}
</script>

<style scoped>
.search-form {
    display: flex;
    align-items: center;
}

.markdown-container {
    margin-top: 10px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #ebeef5;
    overflow: auto;
}

.no-data {
    color: #999;
    text-align: center;
    padding: 20px;
}

/* Markdown 内容样式 */
.markdown-container :deep(pre) {
    background: #2d2d2d;
    color: #f8f8f8;
    padding: 10px;
    border-radius: 5px;
    overflow-x: auto;
}

/* Mermaid 图表居中 */
:deep(.mermaid) {
    text-align: center;
    margin: 20px;
}
</style>

<style>
/* Mermaid 图表居中 */
.mermaid {
    text-align: center;
    margin: 20px;
}
</style>